<template>
	<vCommonPage class="mzyyQrghxx" type="1" :typeChose="$route.query.typeChose" :title="$route.query.code == 'mzyy' ? '门诊预约':'门诊挂号'"
		:mzlx="$route.query.mzlx">
		<div slot="customContent" style="width: 100%">
			<div class="CenterBox">
				<div class="left flex">
					<div class="patientName">患者：{{$store.state.user.userinfo.patientName}}</div>
					<div class="patientName">性别：{{$store.state.user.userinfo.sex == '2'?'女':'男'}}</div>
					<div class="patientName" v-if="age">年龄：{{age}}</div>
				</div>
			</div>
			<div class="TextBox">
				<div class="TextBoxItem flex" v-for="(item,index) in detailList" :key="'info1-'+index">
					<div class="TextLeft">{{item.name}}</div>
					<div class="TextRight">{{item.value}}</div>
				</div>
				<div class="xyZ">
					<el-button class="TextBoxBtom" @click="gotoChosePay()">
						确认
					</el-button>
				</div>
			</div>
			<div class="bottomBox">
				<el-button type="primary" class="BtnTextHome" @click="goBack()">返回</el-button>
				<el-button type="primary" class="BtnTextHome" @click="goBackHome()">首页</el-button>
			</div>
		</div>
	</vCommonPage>
</template>

<script>
  import {
    lockReg,
    registerPre,
    regCheckUp,
    preferentialInfo, getRegisterInfo
  } from "@api/apiBox/mzyyAndMzgh"
  import {MessageBox} from "element-ui";
  import {settlePack, settleParse} from "@api/apiBox/MedInsTradeYn";
  import {Printerconf} from "@api/tools/rprinter";
	export default {
		name: "mzgh",
		data() {
			return {
				detailList: [{
						name: '科室名称:',
						value: this.$route.query.mzlx == 0 || this.$route.query.mzlx == 3 ? this.$store.state
							.appointment.department.deptName : this.$store.state.appointment.doctor.deptName
					},
					{
						name: '号别:',
						value: this.$route.query.mzlx == 0 || this.$route.query.mzlx == 3 ? '普通号' : '名医号'
					}, {
						name: '挂号费用类型:',
						value:'自费'
						// value: this.$store.state.appointment.doctor.charactor
					}, {
						name: '挂号时间:',
						value: this.$store.state.appointment.regInfo.regTime
					}, {
						name: '挂号费:',
						value: '￥' + this.$store.state.appointment.doctor.regFee
					}
				],
				age: this.ages(this.$store.state.user.userinfo.birthday),
				regFee: this.$store.state.appointment.doctor.regFee,
				formData: {
					"cardNo": this.$store.state.appointment.cardNo, //卡片编号
					"cardType": this.$store.state.appointment.card.num, //卡片类别
					"deptAddress": this.$store.state.appointment.department.address, //门诊地址
					"deptId": this.$store.state.appointment.department.deptId, //门诊ID
					"deptName": this.$store.state.appointment.department.deptName, //门诊名字
					"doctorId": this.$store.state.appointment.doctor.doctorId, //医生ID
					"doctorName": this.$store.state.appointment.doctor.doctorName, //医生名字
					"hospitalId": this.$store.state.terminfo.hospId, //医院ID
					"idNo": this.$store.state.user.userinfo.idNo, //身份证号码
					"idType": this.$store.state.user.userinfo.idType, //身份证类别
					"ipAddress": this.$store.state.terminfo.ipAddress, //ip地址
					"orderId": "", //订单ID暂时不明白
					"orderType": "1", //1: 挂号 订单   2: 缴费订单3: 处方流转订单  4: 处方流转快递订单5:  预交金充值订单
					"patientAge": this.$store.state.user.userinfo.patientAge, //患者年龄
					"patientId": this.$store.state.user.userinfo.patientId, //患者ID
					"patientName": this.$store.state.user.userinfo.patientName, //患者姓名
					"patientPhone": this.$store.state.user.userinfo.mobile, //患者手机
					"patientSex": this.$store.state.user.userinfo.sex, //患者性别
					"periodId": this.$store.state.appointment.regInfo.periodId,
					"schedulingId": this.$store.state.appointment.regInfo.schedulingId, //排班ID
					"regChannel": "0", //预约渠道 0：自助机
					"regDate": this.$store.state.appointment.date, //预约日期
					"regTime": this.$store.state.appointment.regInfo.regTime, //预约时间
					"regId": this.$store.state.appointment.regInfo.regId, //排班ID
					// "status": "1", //支付状态 1下单2支付成功3下单成功但超时未支付 4取消订单
					"termId": this.$store.state.terminfo.terminfo.termId, //终端ID
					"totalFee": this.$store.state.appointment.doctor.regFee, //挂号费
					"userId": this.$store.state.user.userinfo.userId, //用户ID
					"regTypeId": this.$store.state.appointment.doctor.regTypeId, //医生类别ID  挂号类别 1专家 2普通
					"title": this.$store.state.appointment.doctor.title ,//医生职称
					selfFee: this.$store.state.appointment.doctor.regFee //挂号费
				},
        pconf: new Printerconf(), //初始化凭条打印
			};
		},
		methods: {
			ReckonTime() {},
			//前往选择支付方式
			async gotoChosePay() {
				let regStartTime = "";
				console.log(this.$store.state.appointment, '医生缓存')
				let data = {
					data: this.formData,
					that: this
				};
				this.$store.dispatch("user/updatechargefee", this.regFee); //支付金额 总费用
				this.$store.dispatch("appointment/updateAppointmentInfo", data); //存储锁单信息 -- 没有订单ID
				//锁号
				let res = await lockReg(data);
				this.$store.dispatch("appointment/updateAppointmentInfo", res.data); //存储锁单信息
				// this.$router.push({
				// 	name: 'mzcz',
				// 	query: {
				// 		title: this.$route.query.code == 'mzyy' ? '门诊预约' : '门诊挂号',
				// 		code: this.$route.query.code
				// 	}
				// })
        //提示挂号完成，直接打印小票
        let _this = this;
        MessageBox.alert('挂号成功！请领取小票！', {
          confirmButtonText: "打印",
          callback: action => {
            _this.openPrintTip();
          }
        });
			},
      //1:报告打印机,2:凭条打印机,3:身份证读卡器
      async openPrintTip() {
        //获取全部报告详情 点击全部打印
        this.closeYinying();
        let code = this.$route.query.code;
        console.log("进入打印方法...",code);
        localStorage.setItem("hisVisitNo","")
        if (code == 'mzyy') {
          //获取打印凭条接口
          let registerData = {
            data: {
              queueNo: this.$store.state.appointment.appointmentInfo.queueNo
            },
            that: this
          }
          const registerInfo = await getRegisterInfo(registerData);
          console.log(registerInfo, 'registerInfo')
          console.log(this.$store.state, '打印')
          console.log('val.$store.state.appointment.appointmentInfo', this.$store.state.appointment
              .appointmentInfo)
          // this.tipText = '您的预约凭证正在打印，请领取后再离开……';
          let printdata = {
            name: this.getPrintDeviceNameByPort('2'),
            data: registerInfo,
            hisVisitNo: this.hisVisitNo
          }
          console.log(this.getPrintNameByPort("2"))
          await this.pconf.mzyyprint(this.getPrintNameByPort("2"), this, printdata).then(res => {
            console.log(res)
            this.tipText = '预约凭证已打印，感谢您的使用！';
            setTimeout(() => {
              this.$router.push('/');
            }, 3000);
          }).catch(e => {
            console.log(e)
            this.tipText = '抱歉，预约凭证打印失败，请联系管理员……';
          });
        } else if (code == 'mzgh') {
          // this.tipText = '您的挂号凭证正在打印，请领取后再离开……';
          //获取打印凭条接口
          let registerData = {
            data: {
              queueNo: this.$store.state.appointment.appointmentInfo.queueNo
            },
            that: this
          }
          const registerInfo = await getRegisterInfo(registerData);
          console.log(registerInfo, 'registerInfo')
          console.log(this.$store.state, '打印')
          // this.tipText = '您的预约凭证正在打印，请领取后再离开……';
          let printdata = {
            name: this.getPrintDeviceNameByPort('2'),
            data: registerInfo,
            hisVisitNo: this.hisVisitNo
          }
          await this.pconf.mzghprint(this.getPrintNameByPort("2"), this, printdata).then(res => {
            console.log(res)
            this.tipText = '挂号凭证已打印，感谢您的使用！';
            setTimeout(() => {
              this.$router.push('/');
            }, 3000);
          }).catch(e => {
            console.log('抱歉，门诊缴费凭证打印失败，请联系管理员……')
            this.tipText = '抱歉，挂号凭证打印失败，请联系管理员……';
          });
        } else if (code == 'mzjf') {
          //如果是医保支付的话并且结算完现金 需要通知his医保结算  现金支付不为0
          console.log('个人支付金额:', this.$store.state.user.userpay)
          if (this.$store.state.user.isYbPay && this.$store.state.user.userpay > 0) {
            console.log('使用医保支付，并且使用微信支付宝支付 通知his。')
            this.payinfo.data.orderId = this.$store.state.recipel.erCodeInfo.orderId;
            this.payinfo.data.IPatientId = this.$store.state.user.IPatientId; //医保个人编号
            this.payinfo.data.IVisitNo = this.$store.state.user.IVisitNo;  //医保流水号
            let  settlePackRes =  await settlePack(this.payinfo);
            console.log("医保结算入参：");
            console.log(settlePackRes.data);
            //唤醒医保组件
            var settleRtn = await this.YB.Trade('BMZJF002', settlePackRes.data);
            console.log("调用医保机器返回：",settleRtn);
            let settleParseItemData = typeof settleRtn == "string" ? JSON.parse(settleRtn) : {};
            console.log("调用医保机器返回解析：",settleParseItemData);
            //获取自费金额
            let settleParseData = {
              data: settleParseItemData,
              that: this
            }
            let settleParseRes = await settleParse(settleParseData);
            let records = this.$store.state.recipel.records;
            records.paidOrdersSuccessByMzjfRes = settleParseRes.data;
            this.$store.dispatch("recipel/updateRecordsInfo", records); //存储缴费订单信息
          }
          // this.tipText = '您的门诊缴费凭证正在打印，请领取后再离开……';
          console.log(this.$store.state, '请领取后再离开')
          let printdata = {
            name: this.getPrintDeviceNameByPort('2'),
            paidOrdersSuccessByMzjfRes: this.paidOrdersSuccessByMzjfRes
          }
          await this.pconf.mzjsprint(this.getPrintNameByPort("2"), this, printdata).then(res => {
            console.log('打印结算，打印结果：')
            console.log(res)
            this.tipText = '门诊缴费凭证已打印，感谢您的使用！';
            setTimeout(() => {
              this.$router.push('/');
            }, 3000);
          }).catch(e => {
            this.tipText = '抱歉，门诊缴费凭证打印失败，请联系管理员……';
          });
        } else if (code == 'yjjcz') {
          // this.tipText = '您的门诊充值凭证正在打印，请领取后再离开……';
          console.log(this.$store.state, '请领取后再离开')
          let printdata = {
            name: this.getPrintDeviceNameByPort('2'),
            data: {
              // balance: this.$store.state.recipel.records.amount + this.$store.state.user.userinfo.balance
            }
          }
          await this.pconf.zyczprint(this.getPrintNameByPort("2"), this, printdata).then(res => {
            console.log(res)
            this.tipText = '住院充值凭证已打印，感谢您的使用！';
            setTimeout(() => {
              this.$router.push('/');
            }, 3000);
          }).catch(e => {
            console.log(e)
            this.tipText = '抱歉，门诊充值凭证打印失败，请联系管理员……';
          });
        }
      },
			async getRegPriceInfo() {
				let data = {
					data: this.formData,
					that: this
				};
				//锁号调用这个接口
				const regCheckUpResponse = await regCheckUp(data);
				//获取优惠价格
				// let preferentialInfoData = {
				// 	data: {
				// 		patientId: this.$store.state.user.userinfo.patientId, //患者ID
				// 		itemId: this.$store.state.appointment.regInfo.itemId
				// 	},
				// 	that: this
				// }
				// const preferentialInfoResponse = await preferentialInfo(preferentialInfoData);
				// let doctorInfo = this.$store.state.appointment.doctor;
				// this.regFee = preferentialInfoResponse.data.cashFee;
				// this.formData.totalFee = preferentialInfoResponse.data.cashFee;
				// doctorInfo.regFee = preferentialInfoResponse.data.cashFee;
				// doctorInfo.charactor = preferentialInfoResponse.data.charactor;
				// doctorInfo.preferentialFee = preferentialInfoResponse.data.preferentialFee;
				// this.$store.dispatch("appointment/updateDoctor", doctorInfo); //存储新的优惠信息
				// console.log(this.$store.state.appointment.doctor, 'this.$store.state.appointment.doctor')
				// this.detailList[2].value = this.$store.state.appointment.doctor.charactor;
				// this.detailList[4].value = this.$store.state.appointment.doctor.regFee;
			},
			//初始化表单信息
			async initData() {
				//获取锁号价格
				await this.getRegPriceInfo();
			},
			ages(str) {
				if (!str) {
					return '';
				}
				var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
				if (r == null) return false;
				var d = new Date(r[1], r[3] - 1, r[4]);
				if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
					var Y = new Date().getFullYear();
					return (Y - r[1]);
				}
				return ("");
			}
		},
		computed: {

		},
		components: {},
		mounted() {},
		created() {
			console.log(this.$store.state, 'sss')
			this.initData();
		}
	};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	@import "../../assets/css/mzghYy/qrghxx.scss";


</style>
<style>
	.mzyyQrghxx .addChose{
	}
</style>
